const express = require('express')
const router = express.Router()
const {Article} = require('../../models')
const {Op} = require('sequelize')
const {NotFoundError, success, failure} = require('../../utils/response')

/**
 * 查询文章列表
 * GET /admin/articles
 */
router.get('/', async (req, res) => {
	try {
		const query = req.query

		// 当前页码，如果不传，默认为1
		const currentPage = Math.abs(Number(query.currentPage)) || 1
		// 每页显示条数，如果不传，默认为10
		const pageSize = Math.abs(Number(query.pageSize)) || 10
		// 计算 offset
		const offset = (currentPage - 1) * pageSize

		const condition = {
			order: [['id', 'desc']], limit: pageSize, offset: offset
		}

		// 搜索
		if (query.title) {
			condition.where = {
				title: {
					[Op.like]: `%${query.title}%`
				}
			}
		}

		const {count, rows} = await Article.findAndCountAll(condition)

		success(res, '后台文章列表接口', {
			articles: rows, pagination: {
				total: count, currentPage, pageSize
			}
		})
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 文章详情查询
 * GET /admin/articles/1
 */
router.get('/:id', async (req, res) => {
	try {
		const article = await getArticles(req)
		success(res, '后台文章列表接口', article)
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 创建文章
 * POST /admin/articles
 */
router.post('/', async (req, res) => {
	try {
		// 过滤白名单
		const body = filterBody(req)
		const article = await Article.create(body)
		success(res, '创建文章成功', article, 201)
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 删除文章
 * DELETE /admin/articles/:id
 * @type {Router}
 */
router.delete('/:id', async (req, res) => {
	try {
		const id = req.params.id
		const article = await getArticles(req)
		await Article.destroy({where: {id}})
		success(res, '删除文章成功')
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 更新文章
 * PUT /admin/articles/:id
 * @type {Router}
 */
router.put('/:id', async (req, res) => {
	try {
		const {id} = req.params
		const article = await getArticles(req)
		const body = filterBody(req)
		await Article.update(body, {where: {id}})
		success(res, '更新文章成功')
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 公共方法：查询文章
 * @param req
 * @returns {Promise<Model>}
 */
async function getArticles(req) {
	const {id} = req.params
	const article = Article.findByPk(id)
	if (!article) {
		throw new NotFoundError(`ID：为${id}的文章没找到`)
	}
	return article
}

/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
	return {
		title: req.body.title,
		content: req.body.content
	}
}

module.exports = router